package com.njupt.yanglonglong.report.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njupt.yanglonglong.report.demo.common.Result;
import com.njupt.yanglonglong.report.demo.dto.CourseDto;
import com.njupt.yanglonglong.report.demo.dto.StudentInfo;
import com.njupt.yanglonglong.report.demo.entity.RAppliedStudent;
import com.njupt.yanglonglong.report.demo.entity.RUser;
import com.njupt.yanglonglong.report.demo.service.RAppliedStudentService;
import com.njupt.yanglonglong.report.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @className: RAppliedStudentConttoller
 * @Description: 学生申请表controller
 * @author: lpl
 * @date: 2021/4/29 22:26
 */
@RestController
@Slf4j
@CrossOrigin
public class RAppliedStudentController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    RAppliedStudentService rAppliedStudentService;

    /**
     * 学生申请进入课程 需要courseId、teacherId、(stu_id(user_id))
     *
     * @param request stu_id(user_id)
     * @param map     courseId、teacherId
     * @return isSuccess
     */
    @RequestMapping("/applyCourse")
    public Result<JSONObject> applyCourse(HttpServletRequest request, @RequestBody HashMap<String, String> map) {
        JSONObject res = new JSONObject();
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        log.info("/applyCourse接到请求" + map + " user: " + user);
        String courseId = map.get("courseId");
        String teacherId = map.get("userId");
        String teamIds = map.get("team");


        if (courseId == null || teacherId == null) {
            log.error("/applyCourse插入数据 " + map + " 失败,因为courseId或teacherId为空");
            res.put("msg", "申请失败");
            return Result.error(res);
        }

        RAppliedStudent rAppliedStudent = new RAppliedStudent();
        rAppliedStudent.setStuId(user.getUserId());
        rAppliedStudent.setCourseId(courseId);
        rAppliedStudent.setTeacherId(teacherId);
        rAppliedStudent.setState(1);

        if (teamIds != null) {
            String[] student = teamIds.split(",");
            for (int i = 0; i < student.length; i++) {
                if (student[i].equals(user.getUserId())) {
                    break;
                }
                if (i == student.length - 1 && !student[i].equals(user.getUserId())) {
                    teamIds = user.getUserId() + "," + teamIds;
                }
            }
            rAppliedStudent.setTeamerIds(teamIds);
        }
        if (teamIds != null) {
            saveTeamCourseInfo(rAppliedStudent, teamIds);
        } else {
            rAppliedStudentService.save(rAppliedStudent);
        }
        res.put("msg", "已经发起选课申请，请等待老师审核");
        return Result.success(res);
    }

    private void saveTeamCourseInfo(RAppliedStudent rAppliedStudent, String teamIds) {
        rAppliedStudent.setTeamerIds(teamIds);
        String[] student = teamIds.split(",");
        for (String s : student) {
            rAppliedStudent.setStuId(s);
            rAppliedStudentService.save(rAppliedStudent);
        }
    }

    /**
     * /deleteApplyCourse接口，根据stu_id、courseId删除申请表中的数据
     *
     * @param request stu_id
     * @param map     courseId、teacherId(userId)
     * @return isSuccess
     */
    @RequestMapping("/deleteApplyCourse")
    public Result<JSONObject> deleteApplyCourse(HttpServletRequest request, @RequestBody HashMap<String, String> map) {
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        log.info("/deleteApplyCourse接到请求 map:" + map + "操作学生信息：" + user);

        Map<String, Object> objectMap = new HashMap<>();
        objectMap.put("course_id", map.get("courseId"));
        objectMap.put("teacher_id", map.get("userId"));
        objectMap.put("stu_id", user.getUserId());

        boolean remove = rAppliedStudentService.removeByMap(objectMap);
        JSONObject res = new JSONObject();
        if (!remove) {
            log.error("/deleteApplyCourse删除数据 " + user.getUserId() + map + " 失败");
            res.put("msg", "取消失败");
            return Result.error(res);
        }
        res.put("msg", "已经发起选课申请，请等待老师审核");
        return Result.success(res);
    }


    /**
     * 通过teacher_id查询所有申请的学生
     *
     * @param request teacher_id
     * @return StudentInfoList
     */
    @RequestMapping("/queryAppliedStuList")
    public Result<JSONObject> queryAppliedStuList(HttpServletRequest request, @RequestBody HashMap<String, String> map) {
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        log.info("/queryAppliedStuList接收用户" + user.getUserId() + "请求");
        JSONObject res = new JSONObject();

        List<StudentInfo> rAppliedStudents = rAppliedStudentService.getStudentInfoList(user.getUserId(), map.get("courseId"));

        if (rAppliedStudents.size() == 0) {
            log.error("/queryAppliedStuList没有查询到用户 " + user.getUserId() + " 信息");
            res.put("msg", "目前没有学生申请你的课程");
            return Result.error(res);
        }
        log.info("/queryAppliedStuList返回数据,data:" + rAppliedStudents);
        res.put("data", rAppliedStudents);
        return Result.success(res);
    }

    /**
     * /updateAppliedStu根据stu_id、course_id、teacher_id更新数据库
     *
     * @param request teacherId
     * @param map     courseId、stuId
     * @return isSuccess
     */
    @RequestMapping("/updateAppliedStu")
    public Result<JSONObject> updateAppliedStu(HttpServletRequest request, @RequestBody HashMap<String, String> map) {

        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        JSONObject res = new JSONObject();
        log.info("/updateAppliedStu接收 user:" + user + "data:" + map);

        QueryWrapper<RAppliedStudent> rAppliedStudentQueryWrapper = new QueryWrapper<>();
        rAppliedStudentQueryWrapper.eq("stu_id", map.get("stuId"))
                .eq("course_id", map.get("courseId"))
                .eq("teacher_id", user.getUserId());
        RAppliedStudent rAppliedStudent = rAppliedStudentService.getOne(rAppliedStudentQueryWrapper);
        if (rAppliedStudent == null) {
            res.put("msg", "操作失败，申请表没有您的数据");
            log.error("/updateAppliedStu更新数值失败 rAppliedStudent为空");
            return Result.error(res);
        }

        rAppliedStudent.setState(Integer.parseInt(map.get("state")));

        if (!rAppliedStudentService.update(rAppliedStudent, rAppliedStudentQueryWrapper)) {
            res.put("msg", "操作失败");
            log.error("/updateAppliedStu更新数值失败 rAppliedStudent:" + rAppliedStudent);
            return Result.error(res);
        }

        log.info("/updateAppliedStu更新成功");
        res.put("msg", "操作成功");
        return Result.success(res);
    }

    /**
     * 学生获取已选的课
     *
     * @param request r
     * @return r
     */
    @RequestMapping("/getCoursesByStuId")
    public Result<JSONObject> getCoursesByStuId(HttpServletRequest request) {
        JSONObject res = new JSONObject();
        String token = request.getHeader("Authorization");
        RUser user = redisUtil.getUser(token);
        if (user == null) {
            return Result.unauthorized();
        }
        log.info("/stuGetApplyCourse接到请求，user：" + user.getUsername());
        List<CourseDto> courseList = rAppliedStudentService.getCoursesByStuId(user.getUserId());
        if (courseList == null) {
            res.put("msg", "获得课程列表失败");
            return Result.error(res);
        }
        res.put("courseList", courseList);
        return Result.success(res);
    }

}
